#include "ezthread.h"

EZThread::EZThread(QObject *parent) :
    QThread(parent)
{
}

void EZThread::run()
{
    while (true) {
        _eventsMutex.lock();

        EZRunFuncEvent *event = 0;
        if(_events.size() > 0){
            event = _events.at(0);
            event->_runFuncMutex.lock();
        }
        _eventsMutex.unlock();

        if(event){
            QObject *obj = event->_target;
            EZThreadCallBack0 callBack = event->_callBack;
            if(obj && callBack){
                (obj->*callBack)(this);
            }
            event->_runFuncMutex.unlock();

            _eventsMutex.lock();
            _events.removeAt(0);
            event->Release();
            _eventsMutex.unlock();

        }else{
            _eventsMutex.lock();
            _eventWaitCondition.wait(&_eventsMutex);
            _eventsMutex.unlock();
        }
    }
}

void EZThread::addRunFunc(EZRunFuncEvent *event)
{
    _eventsMutex.lock();
    event->Retain();
    _events.append(event);
    _eventWaitCondition.wakeAll();
    _eventsMutex.unlock();
}
void EZThread::cancelRunFunc(EZRunFuncEvent *event)
{
    _eventsMutex.lock();
    event->_runFuncMutex.lock();
    int index = _events.indexOf(event);
    if(index>=0){
        _events.removeAll(event);
    }
    event->_runFuncMutex.unlock();
    _eventsMutex.unlock();
}
